#!/bin/sh
# - dockerfile_url

# exit 1 if openEuler failed
# exit 0 if
# - no centos support
# - centos failed

. $LKP_SRC/lib/debug.sh
. $LKP_SRC/lib/log.sh
. $LKP_SRC/lib/handle_dockerfile.sh

[ -n "$dockerfile_url" ] || die "dockerfile_url is empty"

declare -i nr_openeuler_fail=0
declare -i nr_openeuler_success=0
declare -i dockerfile_count=0

fit_repo()
{
	yum reinstall -y git
	git clone "$dockerfile_url" "$BENCHMARK_ROOT/src/"
	dockerfile_path="$(find "$BENCHMARK_ROOT/src/" -type f -name "*Dockerfile*" | xargs grep -HE '^FROM centos:(centos|)[78]')"
	dockerfile_count=$(( $(echo $dockerfile_path | awk '{print NF}') / 2 ))
	[ -n "$dockerfile_path" ] || {
		echo "current-repo-not-support-centos: 1"
		exit 0
	}
}

openeuler_ready()
{
	docker load < $BENCHMARK_ROOT/openeuler_docker/openeuler-20.03-lts-v1.tar
}

build_centos()
{
	cd ${file%/*}
	if [ -f "build.sh" ] && [ -x "build.sh" ]; then
		./build.sh || return 1
	else
		docker build -f "$dockerfile_name" -t "${image}_$1_$index" . || return 1
	fi
}

build_openeuler()
{
	docker build -f "$dockerfile_name" -t "${image}_$1_$index" . >> $TMP_RESULT_ROOT/${image}_$1_$index 2>&1
	[ $? != 0 ] && {
		let nr_openeuler_fail++
		echo "${image}_$index.build.fail: 1"
		return 1
	}
	echo "${image}_$index.build.success: 1"
	let nr_openeuler_success++
	return 0
}

docker_run()
{ 
	docker_run_cmd="docker run -d --name ${image}_$1_$index ${image}_$1_$index"
	[ $1 == "openeuler" ] && {
		docker_run_cmd="${docker_run_cmd} >> $TMP_RESULT_ROOT/${image}_$1_$index 2>&1"
	}

	eval $docker_run_cmd

	docker_stats=$(docker inspect -f '{{.State.Running}}' $image_$1_$index)
	[ $docker_stats == "false" ] && {
		[ $1 == "openeuler" ] && echo "${image}_$index.run.fail: 1"
		return 1
	}

	[ $1 == "openeuler" ] && echo "${image}_$index.run.success: 1"
}

handle_build_result()
{
	if [ "$nr_openeuler_fail" != 0 ]; then
		echo "openeuler_build.nr_failed: $nr_openeuler_fail"
		echo "openeuler_valid_url: $dockerfile_url"
		exit 1
	# centos all success, openeuler all success
	elif [ "$nr_openeuler_success" == "$dockerfile_count" ]; then
		echo "openeuler_valid_url: $dockerfile_url"
		exit 0
	fi
}

build()
{
	dockerfile_name="${file##*/}"
	dockerfile_name="${dockerfile_name%:*}"
	image=$(echo "$file" | awk -F '/' '{print $5}' | tr 'A-Z' 'a-z')

	build_centos "centos" > /dev/null 2>&1 || return 1
	handle_dockerfile "$dockerfile_name"
	build_openeuler "openeuler"
	[ $? != 0 ] && return 1
}

run()
{
	docker_run "centos" > /dev/null 2>&1
	[ $? != 0 ] && return 1
	docker_run "openeuler"
}

centos_docker()
{
	index=1
	for file in $dockerfile_path
	do
		[[ $file =~ ^centos ]] && continue

		build
		[ $? = 0 ] && run
		let index++
	done
}

docker_test()
{
	fit_repo
	openeuler_ready
	centos_docker
	handle_build_result
}

docker_test
